<template>
   <div class="main">
    <Bread></Bread>
    <el-card>
        <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false" style="background: #E6A23C;color:#fff;"></el-alert>
        <el-col :span="24">
            <div class="zhsLeft">
                <span>选择商品分类:</span>
                    <el-cascader
                        expand-trigger="hover"
                        v-model="selectList"
                        :options="cateList"
                        :props="cateProps"
                        @change="handleChange">
                    </el-cascader>
            </div>
                <el-tabs v-model="activeName" @tab-click="handleClick">
                  <el-tab-pane label="动态参数" name="many">
                      <template>
                        <el-col :span="1">
                          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数</el-button>
                        </el-col> 
                        <el-table :data="getManyData" border stripe>
                            <el-table-column type="expand">
                                <template slot-scope="scope">
                                  <el-tag @close="tagHandClose(index,scope.row)" closable v-for="(item,index) in scope.row.attr_vals" :key="index">{{item}}</el-tag>
                                  <el-input
                                      class="input-new-tag"
                                      v-if="scope.row.inputVisible"
                                      v-model="scope.row.inputValue"
                                      ref="saveTagInput"
                                      size="small"
                                      @keyup.enter.native="handleInputConfirm(scope.row)"
                                      @blur="handleInputConfirm(scope.row)"
                                      style="width:150px;"
                                    >
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="#"></el-table-column>
                            <el-table-column  label="参数名称" prop="attr_name"></el-table-column>
                            <el-table-column  label="操作">
                                    <template slot-scope="scope">
                                    <el-button type="primary" size="mini" icon="el-icon-edit" @click="editShowDialog(scope.row.attr_id)">修改</el-button>
                                    <el-button type="danger" size="mini" icon="el-icon-delete" @click="DeleteParams(scope.row.attr_id)">删除</el-button>
                              </template>  
                            </el-table-column>
                        </el-table>
                      </template>
                  </el-tab-pane>
                  <el-tab-pane label="静态属性" name="only">
                      <template>
                        <el-col :span="1">
                          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性</el-button>
                        </el-col> 
                        <el-table :data="getOnlyData" border stripe>
                            <el-table-column type="expand">
                               <template slot-scope="scope">
                                  <el-tag @close="tagHandClose(index,scope.row)" closable v-for="(item,index) in scope.row.attr_vals" :key="index">{{item}}</el-tag>
                                  <el-input
                                      class="input-new-tag"
                                      v-if="scope.row.inputVisible"
                                      v-model="scope.row.inputValue"
                                      ref="saveTagInput"
                                      size="small"
                                      @keyup.enter.native="handleInputConfirm(scope.row)"
                                      @blur="handleInputConfirm(scope.row)"
                                      style="width:150px;"
                                    >
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="#"></el-table-column>
                            <el-table-column  label="属性名称" prop="attr_name"></el-table-column>
                            <el-table-column  label="操作">
                              <template slot-scope="scope">
                                    <el-button type="primary" size="mini" icon="el-icon-edit" @click="editShowDialog(scope.row.attr_id)">修改</el-button>
                                    <el-button type="danger" size="mini" icon="el-icon-delete" @click="DeleteParams(scope.row.attr_id)">删除</el-button>
                              </template>    
                            </el-table-column>
                        </el-table>
                      </template>
                  </el-tab-pane>
              </el-tabs>
            </el-col>
    </el-card>
      <template>

          <el-dialog :title="'添加'+ titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <el-form :model="addRuleForm" :rules="addRules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
              <el-form-item label="活动名称" prop="attr_name">
                <el-input v-model="addRuleForm.attr_name"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
          </el-dialog>

          <el-dialog :title="'修改'+ titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <el-form :model="editRuleForm" :rules="editRules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
              <el-form-item label="活动名称" prop="attr_name">
                <el-input v-model="editRuleForm.attr_name"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
          </el-dialog>
      </template>
   </div>
</template>

<script>
import paramsApi from "@/api/params.js"
import Bread from '@/components/bread.vue'
export default {
    components:{Bread},
    data(){
      return{
        cateList:[],
        cateProps:{
          value:'cat_id',
          label:'cat_name',
          children:'children'
        },
        // 级联选择器双向绑定的数组
        selectList:[],
        // tab标签默认的名称
        activeName:'many',
        // 动态参数获取数据声明的数组
        getManyData:[],
        // 静态参数获取的数据声明的数组
        getOnlyData:[],
        //添加动态参数或者静态属性弹出窗状态
        addDialogVisible:false,
        // 添加参数的表单对象
        addRuleForm:{
          attr_name:'',
        },
        addRules:{
            attr_name:[
              { required: true, message: '请输入参数名称', trigger: 'blur' },
              { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
            ],
        },
        //动态参数或者静态属性弹出窗状态
        editDialogVisible:false,
        editRuleForm:{
          attr_name:'',
          attr_id:""
        },
        editRules:{
            attr_name:[
              { required: true, message: '请输入参数名称', trigger: 'blur' },
              { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
            ],
        }
    }},
    mounted(){
      this.getCateList();
    },
    methods:{
      async getCateList(){
        const {data,meta} = await this.$axios.get("categories")
        if(meta.status !== 200){
          return this.$message.error(meta.msg)
        }
        this.cateList = data
        this.$message.success(meta.msg)
      },
      handleChange(){
          this.getParamsData()
       },
      handleClick() {
        this.getParamsData()
      },
      async getParamsData(){
          // 证明不是三级分类
        if(this.selectList.length !== 3){
          this.selectList = []
          return
        }
        // 证明选中的是三级分类
        const {data,meta} = await this.$axios.get(`categories/${this.cateId}/attributes`,{
                params:{sel: this.activeName} 
              })
        if(meta.status !== 200){
          return this.$message.error("获取参数失败")
        }
        
         data.forEach(item=>{
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [];
          item.inputVisible = false
          item.inputValue = ''
        })
        // 根据判断获取对应动态参数和属性的数组
        if(this.activeName === "many"){
          this.getManyData = data;
        }else{
          this.getOnlyData = data;
        }
      },
      addDialogClosed(){
        this.$refs.ruleFormRef.resetFields();
      },
      addParams(){
          this.$refs.ruleFormRef.validate(async(valid) => {
          if (valid) {
            const {data,meta} = await this.$axios.post(`categories/${this.cateId}/attributes`,{
                attr_name: this.addRuleForm.attr_name,
                attr_sel: this.activeName
            })
           if(meta.status !== 201){
              return this.$message.error("添加参数失败")
            }
            this.$message.success(meta.msg)
            this.getParamsData();
            this.addRuleForm.attr_name= ''
            this.addDialogVisible = false
          } else {
            return false;
          }
        });
      },
      async editShowDialog(cid){
        const {data,meta} = await this.$axios.get(`categories/${this.cateId}/attributes/${cid}`,{
          params:{ attr_sel:this.activeName }
        })
        if(meta.status !== 200){
          return this.$message.error("修改参数/属性失败")
        }
        this.$message.success(meta.msg)
        this.editRuleForm = data;
        this.editDialogVisible = true
      },
      editDialogClosed(){
        this.$refs.ruleFormRef.resetFields();
      },
      editParams(){
        this.$refs.ruleFormRef.validate(async(valid) => {
          if (valid) {
            const {data,meta} = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editRuleForm.attr_id}`,{
                attr_name: this.editRuleForm.attr_name,
                attr_sel: this.activeName
            })
            if(meta.status !== 200){
              return this.$message.error("更新参数失败")
            }
            this.$message.success(meta.msg)
            this.getParamsData();
            this.editDialogVisible = false
          } else {
            return false;
          }
        });
      },
      async DeleteParams(pId){
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { data,meta } = await this.$axios.delete(`categories/${this.cateId}/attributes/${pId}`)
          if(meta.status !== 200){
            return this.$message.error("删除参数失败")
          }
          this.$message.success(meta.msg)
          this.getParamsData();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      handleInputConfirm(row){
        if(row.inputValue.trim().length === 0){
          row.inputValue = ''
          row.inputVisible = false
          return;
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false;
        this.saveAttrVals(row)
      },
      showInput(info){
        info.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      async saveAttrVals(row){
        const {data,meta} = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
        })
        if(meta.status !== 200){
          return this.$message.error("修改参数献给失败")
        }
        this.$message.success("修改数据项成功")
      },
      tagHandClose(Index,row){
        row.attr_vals.splice(Index,1)
        this.saveAttrVals(row);
      }

    },
    computed:{
      isBtnDisabled(){
        if(this.selectList.length !== 3){
          return true
        }
        return false
      },
      cateId(){
        if(this.selectList.length === 3){
          return this.selectList[2]
        }
        return null;
      },
      titleText(){
        if(this.activeName === 'many'){
          return "动态参数";
        }else{
          return "静态属性";
        }
      }
      
    }
}
</script>

<style lang="scss" scoped>
.main{
    width: 100%;
    height: 100%;
}
.el-alert--warning.is-dark {
    background-color: #E6A23C;
    color: #FFF;
}
.zhsLeft{
    text-align: left;
}
.el-tag{
  margin: 10px;
}
</style>
